<template>
<div class="editSms">
  <el-form :inline="true" ref="smsForm" :rules="rules" :model="smsForm" >
    <el-form-item label="内容性质：">
      <el-select v-model="smsForm.attrId" placeholder="">
        <el-option v-for="item,n in attrs" :value="item.id" :label="item.name" :key="n.toString()"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item class="block-line">
      <h3>发送内容</h3>
      <el-col :span="9">
        <div class="getSmsView">
          <p>收信预览</p>
          <p>通知类短信内容会自动添加短信签名</p>
          <div class="view-box">
            <img src="../../../assets/bg/iPhone_white.png" alt="">
            <div class="speech" v-show="viewCont != ''">
              <div v-html="filterHtmlTags(viewCont)+'，回T退订'"></div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="1">
        <div class="vb-h">addag</div>
      </el-col>
      <el-col :span="14">
        <div class="send-wrap cl">
          <el-form-item label="短信标题" class="sms-fl" prop="title">
            <el-input v-model="smsForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-button class="chooseBtn fr" @click="dialogChooseSmsHad">选择已有</el-button>
          <el-button class="chooseBtn fr" @click="testSendPup">测试发送</el-button>
          <!-- <el-form-item label="短信签名" class="sign-wrap block-line sms-fl">
            <el-select :placeholder="sign[0]" v-model="smsForm.sign">
              <el-option v-for="(index, item) in sign" :key="index" :value="item" :label="index"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="" class="cont-wrap block-line">
            <sms-editor  ref="editor"
              :content.sync="smsForm.content"
              @contentChange="handleEditorChange">
            </sms-editor>
          </el-form-item>
        </div>
      </el-col>
    </el-form-item>
    <el-form-item label="" class="block-line business-wrap">
      <el-checkbox v-model="smsForm.groupType">上传到事业部内容库<em>（直接上传，不审核）</em></el-checkbox>
      <!-- <el-form-item label="" class="block-line appoint-wrap">
        <el-checkbox v-show="smsForm.groupType" v-model="checkedAppoint">指定用户可见<em>（只有指定用户可见，不审核）</em></el-checkbox>
        <div v-show="checkedAppoint" class="appoint-detail"><span>已选 10</span><a href="javascript:;">查看详情</a></div>
      </el-form-item> -->
    </el-form-item>
    <el-form-item v-if="showCommonType" label="" class="block-line">
      <el-checkbox v-model="smsForm.commonType">上传到公共内容库<em>（将提交品牌VI审核）</em></el-checkbox>
    </el-form-item>
  </el-form>
  <el-row class="submit-wrap">
    <el-col :span="24">
      <el-button type="primary" style="width:100px" :loading="isSaving" @click="submitForm('smsForm')">{{smsForm.save?'保存':'返回'}}</el-button>
      <el-button v-if="!smsForm.save" type="primary" :loading="isSaving" style="width:100px" @click="otherSubmitForm('smsForm')">另存为</el-button>
      <el-button type="primary" v-if="smsForm.save" :loading="isSaving" style="width:100px" @click="submitForm('smsForm')">保存并发送</el-button>
    </el-col>
  </el-row>
  <el-dialog
    title="测试发送"
    :visible.sync="dialogTestSend">
    <el-form :inline="true" ref="testForm" :rules="rules" :model="testForm" class="test-wrap">
      <el-form-item label="测试手机号" prop="target">
        <el-input v-model="testForm.target" placeholder="请输入手机号" class="test-phone"></el-input>
      </el-form-item>
      <el-form-item label="验证码" class="vcode-wrap" prop="captcheCode">
        <el-input v-model="testForm.captcheCode" placeholder="请输入验证码" class="test-vcode"></el-input>
        <img class="captchaImg" :src="captchaImg" alt="验证码" @click="getCaptchaImg">
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="testSendSubmit('testForm')">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog
    title="选择已有短信内容"
    :visible.sync="smsForm.dialogChooseSms">
    <sms-choose-had ref="smsChoose" :smsList="smsList" :smsListForm="smsListForm" :smsForm="smsForm" v-on:refreshbizlines="getSmsList"></sms-choose-had>
  </el-dialog>
  <new-send :show.sync="dialogNewSend" :newSendData.sync="newSendItem" ref="sendset"></new-send>
</div>
</template>
<script>
  import {mapActions, mapMutations, mapState} from 'vuex'
  import smsChooseHad from '@/components/common/content/smsChooseHad'
  import smsEditor from '@/components/common/content/smsEditor'
  import newSend from '@/components/common/content/newSend'
  export default {
    data () {
      return {
        smsForm: {
          id: this.$route.params.id === 'add' ? '' : this.$route.params.id,
          attrId: '',
          sign: '',
          title: '',
          content: '',
          groupType: true,
          commonType: false,
          dialogChooseSms: false,
          save: true
        },
        testForm: {
          type: 3,
          captchaKey: '',
          target: '',
          testTitle: '',
          testContent: '',
          captcheCode: ''
        },
        smsListForm: {
          title: '',
          page: 1,
          size: 10
        },
        captchaImg: '',
        checkedAppoint: false,
        sign: ['【欣兆阳】', '【欣兆阳1】', '【欣兆阳2】'],
        clickFlag: false,
        dialogTestSend: false,
        showCommonType: true,
        dialogNewSend: false,
        newSendItem: {
          title: '',
          id: '',
          type: 3
        },
        isSaving: false,
        rules: {
          title: {required: true, message: '请输入短信名称', trigger: 'blur'},
          content: {required: true, message: '请输入短信内容', trigger: 'blur'},
          target: [{required: true, message: '请输入手机号码', trigger: 'blur'},
            {pattern: /^\d{11}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
          captcheCode: {required: true, message: '请输入验证码', trigger: 'blur'}
        }
      }
    },
    mounted () {
      this.initPage()
    },
    components: {
      smsChooseHad, smsEditor, newSend
    },
    computed: {
      ...mapState({
        smsList: state => state.contentManage.smsNewsList,
        smsDetail: state => state.contentManage.smsDetail,
        attrs: state => state.contentManage.contentType,
        viewCont: state => state.contentManage.smsViewCont
      })
    },
    methods: {
      ...mapActions(['getSmsNewsList', 'editSms', 'getSmsDetail', 'getCaptcha', 'testSend', 'getContentTypes']),
      ...mapMutations(['SET_SMS_VIEWCONT']),
      initPage () {
        this.smsForm.id && this.getSmsDetail(this.smsForm.id)
        .then(() => {
          this.smsDetail.groupType = Boolean(this.smsDetail.groupType)
          this.smsDetail.commonType = Boolean(this.smsDetail.commonType)
          this.smsForm = {
            ...this.smsForm,
            ...this.smsDetail
          }
          this.showCommonType = !this.smsDetail.commonType
        })
        this.getContentTypes().then(() => {
          this.smsForm.attrId = this.attrs[0].id
        })
        this.SET_SMS_VIEWCONT('')
      },
      getCaptchaImg () {
        this.getCaptcha().then(res => {
          if (res.data.code === 1) {
            this.captchaImg = 'data:image/png;base64,' + res.data.data.base64Image
            this.testForm.captchaKey = res.data.data.key
          }
        })
      },
      getSmsList () {
        this.getSmsNewsList({...this.smsListForm})
      },
      dialogChooseSmsHad () {
        this.smsForm.dialogChooseSms = true
        this.getSmsList()
      },
      // 去除html标签
      filterHtmlTags (html) {
        return html.replace(/<\/?.+?>/g, '').replace(/ /g, '')
      },
      // 编辑器内容改变
      handleEditorChange (content) {
        // this.smsForm.content = content
        // this.$refs.editor.focusToEnd()
      },
      contentChangeEditor (obj) {
        this.getDetailData(obj.id)
        // this.$refs.editor.setContent(cont)
      },
      // 日期格式化
      dateFormat (date) {
        return this.$date.format(new Date(date), 'YYYY-MM-DD hh:mm:ss')
      },
      // 校验短信长度
      checkSmsLength (cont) {
        if (this.filterHtmlTags(cont).length > 65) {
          this.$message({
            type: 'warning',
            message: '短信内容长度超出限制'
          })
          return false
        }
        return true
      },
      // 保存|返回
      submitForm (form) {
        if (this.smsForm.save) {
          this.smsForm.content = this.$refs.editor.getEditorCont()
          if (!this.checkSmsLength(this.smsForm.content)) {
            return
          }
          this.smsForm.groupType = Number(this.smsForm.groupType)
          this.submitData(form)
        } else {
          this.$router.go(-1)
        }
      },
      // 另存为
      otherSubmitForm (form) {
        this.smsForm.content = this.$refs.editor.getEditorCont()
        if (!this.checkSmsLength(this.smsForm.content)) {
          return
        }
        this.smsForm.id = null
        this.smsForm.commonType = 0 // Number(this.smsForm.commonType)
        this.submitData(form)
      },
      // 提交数据
      submitData (form) {
        this.smsForm.commonType = Number(this.smsForm.commonType)
        this.$refs[form].validate(valid => {
          if (valid) {
            this.isSaving = true
            this.editSms(this.smsForm)
              .then(res => {
                this.isSaving = false
                if (res.data.code === 1) {
                  this.smsForm.id = res.data.data
                  this.$message({
                    type: 'success',
                    message: '提交成功'
                  })
                  this.saveAndSend(this.smsForm.id, this.smsForm.title)
                }
              })
          }
        })
      },
      // 发送设置
      saveAndSend (id, title) {
        this.dialogNewSend = true
        this.newSendItem.title = title
        this.newSendItem.id = id
        this.$refs.sendset.getSendRecord(id)
      },
      // 点击测试发送
      testSendPup () {
        this.dialogTestSend = true
        this.getCaptchaImg()
      },
      // 测试发送
      testSendSubmit (form) {
        this.testForm.testTitle = this.smsForm.title
        this.testForm.testContent = this.$refs.editor.getEditorCont()
        if (this.testForm.testTitle === '') {
          this.$message({
            type: 'warning',
            message: '请输入短信名称'
          })
          this.dialogTestSend = false
          return
        }
        if (this.testForm.testContent === '') {
          this.$message({
            type: 'warning',
            message: '请输入短信内容'
          })
          this.dialogTestSend = false
          return
        }
        if (!this.checkSmsLength(this.testForm.testContent)) {
          return
        }
        this.$refs[form].validate(valid => {
          if (valid) {
            this.testSend(this.testForm)
              .then(res => {
                if (res.data.code === 1) {
                  this.$message({
                    type: 'success',
                    message: '发送成功'
                  })
                  this.dialogTestSend = false
                } else if (res.data.code === 3) {
                  this.getCaptchaImg()
                }
              })
          }
        })
      }
    }
  }
</script>
<style lang="scss">
  .vb-h{
    visibility: hidden;
  }
  .editSms{
    .block-line{display:block;width:100%;}
    .block-line .el-form-item__content{display: block;}
  }
  .getSmsView{
    background: #eff2f7;
    text-align: center;
    padding: 15px 40px 0;
    p{
      text-align: left;
      line-height: 1.6;
    }
    .view-box{
      margin-top: 20px;
      display: inline-block;
      position: relative;
    }
    .speech{
      position: absolute;
      width: 160px;
      min-height: 20px;
      max-height: 160px;
      padding: 5px 10px;
      font-size: 12px;
      word-wrap: break-word;
      word-break: break-all;
      white-space: normal;
      color: #333;
      background-color: #e5e5ea;
      border-radius: 15px;
      top: 85px;
      left: 30px;
      text-align: left;
      line-height: 18px;
      &:before{
        content: ' ';
        position: absolute;
        width: 0;
        height: 0;
        left: -1px;
        bottom: -2px;
        border: 4px solid;
        border-color: #e5e5ea transparent transparent #e5e5ea;
        transform: rotate(30deg);
      }
      > div{
        max-height: 160px;
        overflow: scroll;
      }
      .insert_client_attr{
        color: #333;
        text-decoration: none;
        padding: 0 5px;
        background: #9ff6f5;
      }
    }
  }
  .send-wrap .sms-fl{
    .el-form-item__label, .el-form-item__content{float: left;}
  }
  .sms-cont{
    height: 214px;
    padding: 10px 20px;
    outline-style: none;
  }
  .chooseBtn{
    background: #f9fafc;
    margin-left: 15px;
  }
  .sign-wrap{
    margin: 20px 0;
    .el-select{
      width: 169px;
    }
  }
  .cont-wrap{
    margin-top: 20px;
    // border: 1px solid #ccc;
    .cont-top{
      padding: 5px 15px;
      background: #f9fafc;
      border-bottom: 1px solid #ccc;
      .el-button{
        padding: 7px;
        color: #666;
        min-width: 126px;
      }
    }
    .el-textarea__inner{
      border: none;
      resize: none;
    }
  }
  .business-wrap{
    padding-top: 10px;
    border-top: 1px solid #ccc;
    margin-bottom: 10px;
  }
  .el-checkbox__label em{
    color: #ccc;
  }
  .appoint-wrap{
    margin-left: 25px;
    .appoint-detail{
      margin-left: 25px;
      a{
        margin-left: 25px;
        text-decoration: none;
      }
    }
  }
  .submit-wrap{
    padding: 20px 0;
    border-top: 1px solid #ccc;
    text-align: center;
  }

  .test-wrap{
    .el-form-item{width: 100%;}
    .el-form-item__label{min-width: 92px;text-align: right;}
  }
  .test-phone input{width: 260px;}
  .test-vcode{width: 160px;}
  .captchaImg {height: 36px;}
  .clientAttrWrap{
    text-align: center;
    .el-select{width: 100%;}
    h4{
      margin-top: 20px;
      margin-bottom: 5px;
      text-align: left;
      font-weight: normal;
    }
    .el-button{
      margin-top: 30px;
    }
  }
</style>
